package com.easy.dn.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Picture;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.NestedScrollView;
import android.webkit.WebView;
import android.widget.Toast;

import com.easy.common.baserx.RxSubscriber;
import com.easy.dn.app.AppConstant;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import dn.easy.com.easyto.R;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@SuppressWarnings("deprecation")
public class ContentToPictureUtils {

	private LocalBroadcastManager localBroadcastManager;
	public static String DCIMCamera_PATH = AppConstant.DCIMPATH + "/Camera/";
	public static String imgPath ;

	/**
	 * webView
	 * 
	 * @param context
	 * @param webView
	 */
	public static void webviewContent2Png(Context context, WebView webView) {
		Bitmap bmp = null;
		bmp = captureWebView(webView);
		// new Thread(new WorkThread(bmp)).start();
		saveBitmapToCamera(context, bmp, null);
	}
	private static Bitmap captureWebView(WebView webView) {
		Picture snapShot = webView.capturePicture();
		Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(),
				snapShot.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bmp);
		snapShot.draw(canvas);
		return bmp;
	}


	/**
	 * mScrollView
	 * 
	 * @param context
	 * @param scrollView
	 */
	public static Boolean scrollviewContent2Png(Context context,
												NestedScrollView scrollView) {
		Bitmap bmp = null;
		bmp = getBitmapByView(scrollView);
		bmp = ImageUtil.drawTextToRightBottom(context, bmp, "Created by JobTube", 10, Color.GRAY, 5, 5);
		// new Thread(new WorkThread(bmp)).start();
		return saveBitmapToCamera(context, bmp, null);
	}
	/**
	 * 增加線程管理 顯示效果  生成图片到指定文件夹下
	 * @param context
	 * @param NestedScrollView
	 */
	public static void scrollviewContentToPng(final Context context, final NestedScrollView scrollView) {
		Bitmap bmp = null;
		bmp = getBitmapByView(scrollView);
		bmp = ImageUtil.drawTextToRightBottom(context, bmp, "Created by JobTube", 10, Color.GRAY, 5, 5);
		final Bitmap finalBmp = bmp;
		Observable.create(new Observable.OnSubscribe<Boolean>() {
			@Override
			public void call(Subscriber<? super Boolean> subscriber) {

				subscriber.onNext(saveBitmapToCamera(context, finalBmp, null));
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())  .subscribe(new RxSubscriber<Boolean>(context,true) {
					@Override
					protected void _onNext(Boolean aBoolean) {
						if (aBoolean) {
							Toast.makeText(context, context.getResources().getString(R.string.create_jpg_success), Toast.LENGTH_SHORT).show();
//                    showShare();
						} else {
							Toast.makeText(context, context.getResources().getString(R.string.create_jpg_success), Toast.LENGTH_SHORT).show();
						}
					}
					@Override
					protected void _onError(String message) {
						Toast.makeText(context, context.getResources().getString(R.string.create_jpg_success), Toast.LENGTH_SHORT).show();
					}
				});
	}

	public static Boolean saveBitmapToCamera(Context context, Bitmap bm,
											 String name) {
		File file = null;

		if (name == null || name.equals("")) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			Date curDate = new Date(System.currentTimeMillis());
			name = formatter.format(curDate) + ".jpg";
		}
		imgPath = DCIMCamera_PATH+name;
		file = new File(DCIMCamera_PATH, name);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		try {
			FileOutputStream out = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
			scanFileAsync(context,file.getPath());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;

		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}


//		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//		Uri uri = Uri.fromFile(file);
//		intent.setData(uri);
//		context.sendBroadcast(intent);
		return true;
	}

	public static Bitmap getBitmapByView(NestedScrollView scrollView) {
		int h = 0;
		Bitmap bitmap = null;

		for (int i = 0; i < scrollView.getChildCount(); i++) {
			h += scrollView.getChildAt(i).getHeight();
			scrollView.getChildAt(i).setBackgroundColor(
					Color.parseColor("#ffffff"));
		}

		bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
				Bitmap.Config.RGB_565);
		final Canvas canvas = new Canvas(bitmap);
		scrollView.draw(canvas);
		return bitmap;
	}

	public static void scanFileAsync(Context ctx, String filePath) {
		Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		scanIntent.setData(Uri.fromFile(new File(filePath)));
		ctx.sendBroadcast(scanIntent);
	}

}
